package com.zhuiYun.project.util.validator;

import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.util.ObjectUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;


/**
 * 验证对象参数是否合法
 * @auther zcy
 * @data 2023/3/22 13:35
 */
public class ValidatorUtil {


    /**
     * 创建validator 验证器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 实现校验方法并返回校验结果
     * @param bean
     * @return
     */
    public static ValidationResult validate(Object bean) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean, Default.class);
        if (constraintViolationSet.size() > 0) {
            //有错误
            result.setHasError(true);
            // 将错误结果遍历填充在result结果中
            constraintViolationSet.forEach(constraintViolation -> {
                String errMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                result.getErrorMsgMap().put(propertyName, errMsg);
            });
        }
        return result;
    }

    /**
     * 验证实体对象
     * @param obj
     * @return
     * @throws CommonException
     */
    public static boolean ValidationObject(Object obj) throws CommonException {
        if (ObjectUtils.isNotEmpty(obj)) {
            ValidationResult result = ValidatorUtil.validate(obj);
            if (result.isHasError()) {
                throw new CommonException(EmErrorCode.PARAMETER_VALIDATION_ERROR, result.getErrMsg());
            }
            return true;
        }
        return false;
    }


}
